package com.blb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;

/**
 * 文件下载控制器
 */
@Controller
public class DownloadController {

    public static final String DOWNLOAD_PATH = "D:\\upload-images\\";

    /**
     * 文件下载
     * @param filename 文件名
     * @param response
     */
    @RequestMapping("/download")
    public void download(String filename, HttpServletResponse response) throws IOException {
        File file = new File(DOWNLOAD_PATH + filename);
        if(file.exists()){
            //在浏览器出现下载对话框
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + filename);
            //通过流将文件发送给客户端
            Files.copy(file.toPath(),response.getOutputStream());
        }
    }
}
